#include <stdlib.h>
#include <string.h>

static const char id_str_latest[] = "<td id=\"latest_link\">";

const char *
find_latest_id_ref(const char *webtext)
{
	const char *start = strstr(webtext, id_str_latest);
	if (start == NULL)
		return NULL;
	return start + (sizeof(id_str_latest) - 1);
}

int
copy_latest_ref(const char *begin_ref_text, char *buf, unsigned int sz)
{
	const char *left = strstr(begin_ref_text, "href=\"");
	const char *right = NULL;
	if (left == NULL)
		return -1;
	left += 6;
	right = strchr(left, '"');
	if (!right || right - left + 1 > sz)
		return -1;
	memcpy(buf, left, right - left);
	buf[right - left] = '\0';
	return 0;
}

static void
cp_ver_part(const char **verstr, char *bufp, char tok)
{
	while (**verstr != tok) {
		*bufp = **verstr;
		++ (* verstr);
		++ bufp;
	}
	*bufp = '\0';
}

int
vers_latest(const char *begin_ref_text)
{
	char buf[128];
	char v1, v2;
	short v3;
	const char *cp;
	/* Everything between > and < */
	const char *beg = strchr(begin_ref_text, '>');
	const char *end = NULL;
	if (beg == NULL)
		return -1;
	if (beg) {
		++ beg;
		end = strchr(beg, '<');
	}
	if (end == NULL)
		return -1;
	cp = beg;
	cp_ver_part(&cp, buf, '.');
	v1 = (char)(atoi(buf) & 0xff);
	++ cp;
	cp_ver_part(&cp, buf, '.');
	v2 = (char)(atoi(buf) & 0xff);
	++ cp;
	cp_ver_part(&cp, buf, '<');
	v3 = (short)(atoi(buf) & 0xffff);
	return v1 << 24 | v2 << 16 | v3;
}

int
str_to_ver_id(const char *ptr)
{
	char buf[64];
	char v1, v2;
	short v3;
	const char *cp = ptr;
	cp_ver_part(&cp, buf, '.');
	v1 = (char)(atoi(buf) & 0xff);
	++ cp;
	cp_ver_part(&cp, buf, '.');
	v2 = (char)(atoi(buf) & 0xff);
	++ cp;
	cp_ver_part(&cp, buf, '\0');
	v3 = (short)(atoi(buf) & 0xffff);
	return v1 << 24 | v2 << 16 | v3;
}
